import os
import pandas as pd

def generate_level_scores(df, secondary_weights, meta_cols, output_dir, method_name):
    # 六大一级维度对应的二级指标
    level_mapping = {
        'Level1数字基础设施': ['S1', 'S2', 'S3'],
        'Level2数据治理环境': ['D1', 'D2', 'D3'],
        'Level3数字金融服务': ['F1', 'F2', 'F3'],
        'Level4数字创新支撑': ['T1', 'T2', 'T3'],
        'Level5数字人力资本': ['Q1', 'Q2', 'Q3'],
        'Level6法制环境保障': ['L1', 'L2', 'L3'],
    }

    # 生成加权六维指标得分
    df_level = df[meta_cols].copy()
    level_weights = {}

    for level, cols in level_mapping.items():
        # 从传入的二级指标权重中取出对应权值
        sub_weights = secondary_weights.loc[cols].values
        df_level[level] = df[cols].dot(sub_weights)
        # 一级指标的权重 = 对应三个二级指标权值之和
        level_weights[level] = sub_weights.sum()

    # 构建一级指标权值 DataFrame
    level_weights_df = pd.DataFrame({
        '指标': list(level_weights.keys()),
        '权值': list(level_weights.values())
    })

    # 保存六维得分数据
    level_score_file = os.path.join(output_dir, f"level_scores_{method_name}.csv")
    df_level.to_csv(level_score_file, index=False, encoding='utf-8-sig')

    # 保存一级指标权值
    level_weight_file = os.path.join(output_dir, f"level_weights_{method_name}.csv")
    level_weights_df.to_csv(level_weight_file, index=False, encoding='utf-8-sig')

    return df_level, level_weights_df.set_index('指标')['权值'], level_score_file
